import traceback

from django.shortcuts import render
from rest_framework import permissions

from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView, ListAPIView, UpdateAPIView
from rest_framework.response import Response
from django.forms.models import model_to_dict
from django.db import transaction

from repair.models import HouseInfo
from account.models import Account
from common.redis_utils import RDS

rds = RDS()
repair_key = 'repair'


# Create your views here.

class AddHouseInfo(APIView):
    """
    添加房屋信息表
    """

    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        try:
            # with transaction.atomic():
            user = request.user
            data = request.data
            build_no = data.get('build_no')
            unit_no = data.get('unit_no')
            house_no = data.get('house_no')
            square_metre = data.get('square_metre')
            # TODO 数据类型的验证
            if not all([build_no, unit_no, house_no, square_metre]):
                return Response({'code': 400, 'message': '参数不全'})
            house, _ = HouseInfo.objects.get_or_create(build_no=build_no, unit_no=unit_no, house_no=house_no)
            house.square_metre = square_metre
            house.account = user
            house.save()

            data = model_to_dict(house)
            return Response({'code': 200, 'data': data})
        except:
            error = traceback.format_exc()
            print('000000000000', error)
            return Response({'code': 500, 'message': error})


class GetHoseList(ListAPIView):
    """
    pass
    """
    queryset = HouseInfo.objects.filter()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        result = {'data': serializer.data, 'count': '100', page: 1}

        return Response(result)


class UpdateWorkerStatus(UpdateAPIView):
    """
    更新维修人员状态

    繁忙、离线---》空闲
    """
    def post(self, request):
        user = request.user
        data = request.data
        status = data.get('status')
        # work_id = data.get('work_id')
        if status == 0:
            # 当维修人员状态更新为空闲是，加入到工作等待的队列中
            add_work_user_id(user.id)


class CreatRepairOrder(APIView):
    def post(self, request):
        work_id = allot_work_user_id()


class AdminAllotWork(UpdateAPIView):
    """
    管理员分配工作
    """
    def post(self, request):
        work_id = allot_work_user_id()


def add_work_user_id(user_id):
    redis_list = rds.get_list(repair_key)
    redis_list = [i.decode('utf-8') for i in redis_list]
    if user_id not in redis_list:
        rds.right_push(repair_key, user_id)


def allot_work_user_id():
    """
    分配工作
    """
    user_id = rds.left_pop(repair_key)
    return user_id


def update_repair(order_id, user_id):
    """
    更新维修单状态
    """
    # TODO 修改维修单的状态以及维修人员
    pass


def update_user_status(user, status):
    """
    修改维修人员的状态
    """
    user.update_status(status)
    # user.status = status
    # user.save()
